package com.shun.service

import com.shun.commons.ApiUtils
import com.shun.commons.exception.AppException
import com.shun.entity.User
import com.shun.feign.UserClient
import jodd.datetime.JDateTime
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.Update
import org.springframework.stereotype.Service
import java.util.*

/**
 * Created by Administrator on 2017/8/12.
 */
@Service
class UserService {

    @Autowired
    private lateinit var mongoTemplate: MongoTemplate

    @Autowired
    private lateinit var userClient: UserClient

    @Autowired
    private lateinit var utils: ApiUtils

    fun list(params: Map<String, String>): Any {
        val criteria = Criteria()

        if (params["searchKey"].toString().isNotBlank()) criteria.and("searchKey").regex(params["searchKey"].toString())

        if (params["status"].toString().isNotBlank()) criteria.and("status").`in`(params["status"]!!.split(",").map(String::toInt))
        val query = Query.query(criteria)

        val page = if (params["page"] != null) params["page"].toString().toInt() else 0
        val size = if (params["size"] != null) params["size"].toString().toInt() else 10


        if (page > 0) {
            query.skip((page - 1) * size).limit(size)
        }

        val list = mongoTemplate.find(query, User::class.java)

        return if (page > 0) {
            mapOf(
                    "list" to list,
                    "page" to page,
                    "size" to size,
                    "total" to mongoTemplate.count(query, User::class.java)
            )
        } else {
            list
        }
    }

    //创建用户
    fun create(params: Map<String, String>) {

        requireNotNull(params["mobile"], { "手机号码不能为空" })

        if (exists(params["mobile"] as String)) throw AppException("手机号已存在")

        val info = userClient.get(params["mobile"] as String)

        val user = User()
        user.mobile = params["mobile"] as String

        val clientId = "app_client"

        user.uuid = if ((info == null) || (info.status == 0)) {
            //密码截取手机号码后6位
            val password = params["mobile"].toString().substring(5, 11)

            userClient.create(mapOf(
                    "mobile" to params["mobile"] as String,
                    "client" to clientId,
                    "alias" to params["username"] as String,
                    "password" to password,
                    "type" to "app"
            )).uuid
        } else {
            if (info.clientStatus == 0) {
                userClient.active(params["mobile"]!!, clientId).uuid
            } else {
                info.uuid
            }
        }
        user.createTime = Date()
        user.username = params["username"] as String
        user.status = 1
        user.type = 2
        user.company = params["company"] as String

        user.searchKey = build(user)

        mongoTemplate.insert(user)

    }

    private fun exists(mobile: String) = mongoTemplate.exists(Query.query(Criteria("mobile").`is`(mobile)), User::class.java)

    fun info(mobile: String) = mongoTemplate.findOne(Query.query(Criteria("mobile").`is`(mobile)), User::class.java) ?: throw AppException("用户错误")


    fun build(t: User): String? {
        val keys = getSearchKeys(t)
        t.searchKey = if (keys.isNotEmpty()) {
            val first = utils.stringToPinyin(keys[0]!!, "first")
            val full = utils.stringToPinyin(keys[0]!!, "full")
            arrayOf(first.first(), first, full, *keys).distinct().joinToString(",")
        } else {
            ""
        }
        return t.searchKey
    }

    fun getSearchKeys(t: User) = arrayOf(t.username!!, t.mobile)


    fun save(params: Map<String, String>) {
        requireNotNull(params["mobile"], { "无效的信息" })

        val user = mongoTemplate.findOne(Query.query(Criteria("mobile").`is`(params["mobile"])), User::class.java)
        user.username = params["username"] as String
        user.mobile = params["mobile"] as String

        val searchKey = build(user)
        mongoTemplate.findAndModify(Query.query(Criteria("mobile").`is`(params["mobile"])), Update().set("username", params["username"] as String).set("searchKey", build(user)), User::class.java)
    }


    fun modify(mobile: String, params: Map<String, Any?>) {
        params["status"] ?: throw AppException("参数错误")
        mongoTemplate.findAndModify(Query.query(Criteria("mobile").`is`(mobile)), Update().set("status", params["status"].toString().toInt()), User::class.java)
    }


    fun getSearchKey(searchKey: String) = mongoTemplate.find(Query.query(Criteria("searchKey").regex(searchKey)), User::class.java)
}